<?php

class Silk_Tms_Helper_Pickup extends Mage_Core_Helper_Abstract
{
    protected $shippingId = null;

    public function pickup($incrementId)
    {
        $shipOrder = $this->_initShipOrder($incrementId);
        $shipment = $this->_initShipment($incrementId);
        $shipment->getOrder()->setIsInProcess(true);
        $shipment->register();

        Mage::getModel('core/resource_transaction')
            ->addObject($shipOrder)
            ->addObject($shipment)
            ->addObject($shipment->getOrder())
            ->save();

        $shipment->getOrder()->addStatusToHistory(Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_DELIVERING, '订单开始配送', true);
        $shipment->getOrder()->setStatus(Silk_Tms_Helper_Status::MAGENTO_STATUS_COMPLETE_DELIVERING)->save();
    }

    public function _initShipOrder($incrementId)
    {
        if (!$incrementId) {
            $this->_critical('缺少参数11！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
        }
        $order = Mage::getModel('tms/shipping_order')->load($incrementId, 'increment_id');
        if ($order && $order->getId()) {
            /** @var Mage_Sales_Model_Order $mageOrder */
            $mageOrder = Mage::getModel('sales/order')->load($order->getOrderId());
            if (!$mageOrder || !$mageOrder->getId()) {
                $this->_critical('订单编号为：' . $incrementId . '的订单未找到！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }

            if ($mageOrder->getStatus() != Mage_Sales_Model_Order::STATE_PROCESSING) {
                $this->_critical('订单编号为：' . $incrementId . '的订单状态不正确！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }

            $shippingId = $this->getShippingId();
            /** @var Silk_Tms_Model_Shipping $shipping */
            $shipping = Mage::getModel('tms/shipping')->load($shippingId);
            if (!$shipping || !$shipping->getId()) {
                $this->_critical('运单不存在！', Mage_Api2_Model_Resource::ERROR_CHECKOUT_ORDER_NOT_FOUND);
            }

            /*if ($shipping->isLock() && !Mage::app()->getRequest()->getHeader('Access-Token')) {
                $this->_critical('运单已锁定！！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }*/

            if(Mage::app()->getStore()->getId())
            {
                if ($shipping->getUserId() != $this->getCurrentUserId()) {
                    $this->_critical('无权操作！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
                }
            }
            

            $orderShippingId = $order->getShippingId();
            if ($orderShippingId != $shippingId) {
                $this->_critical('该订单不在当前运单中！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }

            if (!in_array($order->getStatus(), array(
                    Silk_Tms_Helper_Status::STATUS_ORDER_NEW,
                    Silk_Tms_Helper_Status::STATUS_ORDER_PROCESSING,
                ))
                || $mageOrder->hasShipments()
            ) {
                Mage::log('订单编号为：' . $incrementId . '的订单已取货！');
                /*$this->_critical('订单编号为：' . $incrementId . '的订单已取货！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);*/
            }

            $order->setStatus(Silk_Tms_Helper_Status::STATUS_ORDER_PICKED);
            $order->setPickupAt($this->formatDateTime(time()));

            return $order;
        }
        $this->_critical("订单不存在当前运单中！", Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
    }

    /**
     * @param $incrementId
     * @return Mage_Sales_Model_Order_Shipment
     */
    public function _initShipment($incrementId)
    {
        $order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
        $savedQtys = $this->_getItemQtys($order);
        /** @var Mage_Sales_Model_Order_Shipment $shipment */
        $shipment = Mage::getModel('sales/service_order', $order)->prepareShipment($savedQtys);
        return $shipment;
    }

    /**
     * Get requested items qty's from request
     */
    protected function _getItemQtys($order)
    {
        $items = $order->getAllItems();

        $qtys = array();
        foreach ($items as $item) {
            $qtys[$item->getId()] = (int)$item->getQtyOrdered();
        }

        return $qtys;
    }

    protected function getShippingId()
    {
        if (is_null($this->shippingId)) {
            $shippingId = Mage::registry("shipping_id");
            if(!$shippingId) $shippingId = Mage::app()->getRequest()->getParam('id');
            if ($shippingId) {
                $this->shippingId = $shippingId;
            } else {
                $this->_critical('缺少参数12！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
            }
        }

        return $this->shippingId;
    }

    protected function getCurrentUserId()
    {
        $token = Mage::app()->getRequest()->getHeader('Access-Token');
        if ($token) {
            $tokenModel = Mage::getModel('mapi/token')->loadByToken($token);
            if ($tokenModel && $tokenModel->getId()) {
                return $tokenModel->getCustomerId();
            }
        }
        $this->_critical('缺少参数13！', Mage_Api2_Model_Resource::ERROR_UNKNOWN_ERROR);
    }

    protected function formatDateTime($time)
    {
        date_default_timezone_set('Asia/Shanghai');

        if (is_string($time)) {
            $time = strtotime($time);
        }

        return date('Y-m-d H:i:s', $time);
    }

    private function _critical($msg, $code)
    {
        throw new Exception($msg, $code);
    }

}